# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import  urlencode
from common.helper import Helper


class Spider(object):

    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "泰康惠心医疗保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {

            "planA": {
                # 年龄段
                "year": [str(i) for i in range(18, 61)],
                # 性别
                "gender": ["M", "F"],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保障金额
                "money": ["4000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 投保对象
                "payObject": ["本人/父母/配偶"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 性别
                "gender": ["M", "F"],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保障金额
                "money": ["4000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 投保对象
                "payObject": ["子女"]

            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["socialSec"], plan[k]["money"],
                             plan[k]["expire"], plan[k]["payType"], plan[k]["payObject"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None):
        data = {
            "codeFlag": "3",
            "productNo": "A72",
            "poltype": "06" if dt["payObject"] == "子女" else "01",
            "responsibility": "A72",
            "insuredGender": "M",
            "birthday": "{0}-01-01".format(str(2020-int(dt["year"]))),
            "applicantGender": dt["gender"],
            "holderBirthday": "{0}-01-01".format(str(2020-int(dt["year"]))),
            "paymentDuration": "01",
            "paymentMode": "01",
            "insureDuration": "1",
            "socialSecurity": "1" if dt["socialSec"] == "Y" else "0",
            "renewalFlag": "1"
        }
        payload = urlencode( data ).replace("+","")
        r = requests.post( url= domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "grossAnnualStdPremium" in r.text:
            price = r.json()["annualStdPremium"]
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格失败:*%d/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)


if __name__ == '__main__':
    s = Spider()
    s.main()
